package com.example.Controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.Service.*;
import com.example.exception.MyException;
import com.example.pojo.*;
import com.example.util.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@SuppressWarnings({"rawtypes", "unchecked"})
@CrossOrigin
@RequestMapping("/finance")
@RestController
@Api(tags = "订单客户统计")
public class FinanceController {

    @Resource
    private XsCustomertService xScustomertService;
    @Resource
    private AttendanceService attendanceService;
    @Resource
    private UserService userService;
    @Resource
    private PositionSalaryService positionSalaryService;
    @Resource
    private UserSalaryService userSalaryService;
    @Autowired
    private FinanceService financeService;

    @GetMapping("/customer")
    public Result customer(){
       int count=(int) xScustomertService.count();
       List<Table> tableList=new ArrayList<>();
       Table table ;
       for (int i = 0; i <= 2; i++) {
          QueryWrapper<XsCustomer> queryWrapper=new QueryWrapper<>();
          queryWrapper.eq("customer_type",Integer.toString(i));
          double count1=(double) xScustomertService.count(queryWrapper);
          count1=(count1/count)*100;
          if(i == 0){
              table = new Table( (int)count1,"新客户");
          } else if (i == 1){
              table = new Table( (int)count1,"老客户");
          } else {
              table = new Table( (int)count1,"加急客户");
          }
          tableList.add(table);
       }

       Map<String,Object> map=new HashMap<>();
       map.put("count",count);
       map.put("table",tableList);
       return new Result("200","成功",map);
    }

    @GetMapping("/accountAll")
    public Result accountAll(@RequestParam("id") Integer id,
                             @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize){
        Map<String,Object> map=new HashMap<>();
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 提取年份和月份
        int years = currentDate.getYear();
        int months = currentDate.getMonthValue();
//        int day = currentDate.getDayOfMonth();
        int day=31;
        // 判断到没到核算日期
        Calendar calendar = Calendar.getInstance();
        // 设置年份
        calendar.set(Calendar.YEAR, years);
        // 设置月份，注意 Calendar 中月份是从 0 开始计数的，所以要减 1
        calendar.set(Calendar.MONTH, months - 1);
        // 获取该月的最大天数
        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        if (day < days) {
            return new Result<>("400","还未到核算日期");
        }
        QueryWrapper<UserSalary> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("years",years);
        queryWrapper.eq("months",months);
        if(id>0){
            queryWrapper.eq("employee_id",id);
        }
        //分页查出本月份有没有核算
        Page<UserSalary> userSalaryPage =new Page<>(pageNum,pageSize);
        int count = (int) userSalaryService.count(queryWrapper);
        //如果已经核算则查询
        if(count>0){
            userSalaryPage=userSalaryService.page(userSalaryPage,queryWrapper);
            map.put("userSalaryPage",userSalaryPage);
            return new Result<>("200","已核算",map);
        }

        //如果没有进行添加
        // 查出打卡数据
        List<Attendance> attendances = attendanceService.list();
        //罚款数据
        LocalDate now = LocalDate.now();
        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());

        for(Attendance attendance:attendances){
            attendance.setImportContent(attendance.getStatus());
            if(!attendanceService.updateById(attendance)){
                return new Result<>("449","更新失败");
            }
            if(!financeService.updateUId(attendance.getUserid(),years,months,firstDayOfMonth,lastDayOfMonth)){
                return new Result<>("450","更新失败");
            }
        }
        userSalaryPage=userSalaryService.page(userSalaryPage,queryWrapper);
        map.put("userSalaryPage",userSalaryPage);
        return new Result<>("200","计算成功",map);
    }


    @GetMapping("/accounting")
    public Result accounting(@RequestParam("id") Integer id,
                             @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize){
        //查用户
        QueryWrapper<User> userWrapper=new QueryWrapper<>();
        userWrapper.eq("id",id);
        User userAll=userService.getOne(userWrapper);
        Map<String,Object> map=new HashMap<>();
        QueryWrapper<Attendance> queryWrapper1=new QueryWrapper<>();
        if(id!=null&&id>=0){
            if(userAll==null){
                map.put("attendances",null);
                return new  Result("200","查无此人",map);
            }
            queryWrapper1.eq("userid",id);
        }
        Page<Attendance> page = new Page<>(pageNum,pageSize);
        //查出打卡数据
        Page<Attendance> attendances=attendanceService.page(page,queryWrapper1);
        if (attendances==null){
            map.put("attendances",attendances);
            return new  Result("200","查无此人",map);
        }
        List<Attendance> tableList=new ArrayList<>();

        //for循环遍历算出扣款
        for(Attendance attendance:attendances.getRecords()){
           //放入状态计算罚款
           attendance.setImportContent(attendance.getStatus());
           //查对应用户
           QueryWrapper<User> queryWrapper=new QueryWrapper<>();
           queryWrapper.eq("id",attendance.getUserid());
           User user=userService.getOne(queryWrapper);
           //判断矿工，缺卡
           if (attendance.getSalaryDeduction()<1&&attendance.getSalaryDeduction()!=0){
              //查出对应职位工资
              QueryWrapper<PositionSalary> positionSalaryQueryWrapper=new QueryWrapper<>();
              positionSalaryQueryWrapper.eq("position_id",user.getPositionId());
              PositionSalary positionSalary= positionSalaryService.getOne(positionSalaryQueryWrapper);

              //计算罚款
              double salary=positionSalary.getBaseSalary()/30.0;
              if (attendance.getSalaryDeduction()>0.5){
                  salary=salary/0.5;
              }
              attendance.setSalaryDeduction(salary);
           }
           attendance.setUsername(user.getName());
           tableList.add(attendance);
        }
        //存储罚款
        boolean isUpdate=attendanceService.updateBatchById(tableList);
        if(!isUpdate){
            throw new MyException("444","核算失败");
        }
        tableList.clear();
        //再次查询
        attendances=attendanceService.page(page,queryWrapper1);
        if (attendances==null){
            return new  Result("200","查无此人");
        }
        for(Attendance attendance:attendances.getRecords()){
            //放入状态
            attendance.setImportContent(attendance.getStatus());
            boolean salary=attendanceService.updateById(attendance);
            if(!salary){
                return new Result<>("449","更新失败");
            }
            //查对应用户
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("id",attendance.getUserid());
            User user=userService.getOne(queryWrapper);

            attendance.setUsername(user.getName());
            tableList.add(attendance);
        }
        attendances.setRecords(tableList);
        //存储返回
        map.put("attendances",attendances);
        return new Result("200","统核成功",map);
    }

    @GetMapping("/accountOne")
    public Result accounting(@RequestParam("id") Integer id){
        //查用户
        QueryWrapper<User> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("id",id);
        QueryWrapper<Attendance> queryWrapper=new QueryWrapper<>();
        User user=new User();
        List<UserSalary> userSalaryList = new ArrayList<>();
        if (id!=null&&id!=0&&userService.getOne(queryWrapper1)!=null){
            user=userService.getOne(queryWrapper1);
        } else {
            return  new Result("200","查无此人");
        }
        //遍历查工资
            queryWrapper= getAttendanceQueryWrapper(user.getId());

            List<Attendance> attendances=attendanceService.list(queryWrapper);

            Double salary=0.00;
            int day = 0;
            double pay = 0;
            for(Attendance attendance:attendances){
                Double salaryDeduction = attendance.getSalaryDeduction();
                System.out.println("salaryDeduction:"+salaryDeduction);
                salary+=salaryDeduction;
                if (attendance.getSalaryDeduction()==0){
                    day++;
                    if (day>30){
                        break;
                    }
                }
            }

        //查工资
        QueryWrapper<PositionSalary> positionSalaryQueryWrapper=new QueryWrapper<>();
        positionSalaryQueryWrapper.eq("position_id",user.getPositionId());
        PositionSalary positionSalary= positionSalaryService.getOne(positionSalaryQueryWrapper);
        //查扣款等

            UserSalary userSalary=new UserSalary();

            userSalary.setEmployeeId(user.getId());
            userSalary.setName(user.getName());
            userSalary.setPositionId(user.getPositionId());
            userSalary.setDeduction(BigDecimal.valueOf(salary));
            userSalary.setBaseSalary(BigDecimal.valueOf(positionSalary.getBaseSalary()));
            //销售有提成销售额的0.5%
            if (day>30){
                pay=50.00;
            }
            userSalary.setCommission(BigDecimal.valueOf(pay));
            QueryWrapper<UserSalary> wrapper=new QueryWrapper<>();
            wrapper.eq("employee_id",user.getId());
            System.out.println(userSalary);
            UserSalary  userSalary1 = userSalaryService.getOne(wrapper);
            System.out.println(userSalary1);
            if (userSalary1==null){
                boolean isAdd=userSalaryService.save(userSalary);
                if(!isAdd){
                    throw new MyException("469","工资更新失败");
                }
            } else {
                boolean isUpdate=userSalaryService.update(userSalary,wrapper);
                if(!isUpdate){
                    throw new MyException("469","工资更新失败");
                }
            }


            QueryWrapper<UserSalary> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("employee_id",user.getId());
            userSalaryList.add(userSalaryService.getOne(queryWrapper2));

        //存储返回
        Map<String,Object> map=new HashMap<>();
        map.put("userSalary",userSalaryList);
        return new Result("200","工资统核成功",map);
    }

    private static QueryWrapper<Attendance> getAttendanceQueryWrapper(Integer id) {
        QueryWrapper<Attendance> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid", id);
        // 获取当前时间
        Date now = new Date();
        // 创建 Calendar 实例
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        // 将月份减 1
        calendar.add(Calendar.MONTH, -1);
        // 获取一个月前的时间
        Date oneMonthAgo = calendar.getTime();

        // 使用 MyBatis-Plus 查询构造器
        queryWrapper.ge("day_time", oneMonthAgo); // 大于等于一个月前的时间
        queryWrapper.le("day_time", now); // 小于等于当前时间
        return queryWrapper;
    }


    @GetMapping("/count")
    public Result count(){
        int count=(int) xScustomertService.count();
        List<Table> tableList=new ArrayList<>();
        Table table ;
        for (int i = 0; i <= 2; i++) {
            QueryWrapper<XsCustomer> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("customer_type",Integer.toString(i));
            double count1=(double) xScustomertService.count(queryWrapper);
            count1=(count1/count)*100;
            if(i == 0){
                table = new Table( (int)count1,"新客户");
            } else if (i == 1){
                table = new Table( (int)count1,"老客户");
            } else {
                table = new Table( (int)count1,"加急客户");
            }
            tableList.add(table);
        }

        Map<String,Object> map=new HashMap<>();
        map.put("count",count);
        map.put("table",tableList);
        return new Result("200","成功",map);
    }
}
